<?php
/**
 * Created by 张富琼 <zfuqiong@ifreegroup.com>.
 * User: kingzcheung
 * Date: 17-10-10
 * Time: 下午4:21
 */


namespace kingzcheung\migration;


class SqlParse {

    /**
     * @var string SQL文本
     *
     * @author 张富琼 <zfuqiong@ifreegroup.com>
     */
    private $content;

    /**
     * @var string SQL 文件路经
     *
     * @author 张富琼 <zfuqiong@ifreegroup.com>
     */
    private $file;


    private $regexp = "/--\s+.+(\n|\r\n|\r)/";

    public function __construct($file) {
        $this->file = $file;
    }

    /**
     * @return string
     */
    public function getContent() {
        return $this->content = file_get_contents($this->file);
    }

    /**
     * @return array 返回文件解析返回的数组
     *
     * @author 张富琼 <zfuqiong@ifreegroup.com>
     */
    public function sqls() {
        $sqlArray = preg_split($this->regexp, $this->getContent());
        $sqlArray = array_filter($sqlArray, function ($v, $k) {
            return $this->sqlFilter($v);
        }, ARRAY_FILTER_USE_BOTH);
        $sqls     = array_map(function ($value) {
            return trim($value);
        }, $sqlArray);


        return $sqls;
    }


    /**
     * 过滤空,删除数据库,查询语句
     *
     * @param $sql
     * @return bool
     *
     * @author 张富琼 <zfuqiong@ifreegroup.com>
     */
    public function sqlFilter($sql) {
        if (!empty($sql)) return true;
        if (strpos(strtoupper($sql), 'DROP DATABASE') === false) return true;
        if (strpos(strtoupper($sql), 'SELECT') === false) return true;

        return false;
    }
    
}